package userModuleApi

import (
	"KumquatDrivesServices/common/res"
	"KumquatDrivesServices/global"
	"KumquatDrivesServices/model"
	"KumquatDrivesServices/utils"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

type UpdateUserNickNameRequest struct {
	NickName string `json:"nickName" binding:"required"`
}

func (UserModuleApi) UpdateUserNickName(c *gin.Context) {
	var req UpdateUserNickNameRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		logrus.Error("UpdateUserNickNameRequest bind error: ", err)
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	userId := utils.GetUserId(c)
	if err := global.DB.Model(&model.UserModel{}).Where("id =?", userId).Update("nick_name", req.NickName).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			res.FailWithCode(res.USER_NOT_EXIST, c)
			return
		}
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	res.OkWithData(map[string]string{
		"nickName": req.NickName,
	}, c)
}
